import {getAdviceDetail} from "../../api/api";
import Util from "../../utils/util";

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: false,//是否加载中
    loadend: false,//是否加载完毕
    loadTitle: '下拉加载更多',//提示语
    lists: [],//
    page: 1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    const id = options.id

    Util.chekWxLogin().then(res => {
      that.setData({
        userInfo: res.userInfo,
      });

      getAdviceDetail(id).then(res => {
        this.setData({
          advice: res.data.advice,
        })
      }).catch(errmsg => {
        Util.Tips({title: errmsg});
      });
    });
  },
  
  previewMutiImage: function (event) {
    let imgList = this.data.advice.pictures || [];
    if (imgList.length == 0)
      return;

    const key = event.currentTarget.dataset.key
    let src = "";
    if (!Util.isEmpty(imgList[key]))
      src = Util.previewCdnImage(imgList[key].path, 750, 0, 1)

    const urls = [];
    for (let i = 0; i < imgList.length; i++) {
      urls.push(Util.previewCdnImage(imgList[i], 750, 0, 1));
    }
    if (urls) {
      wx.previewImage({
        current: src,
        urls: urls,
      });
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  copyTxt: function (event) {
    const txt = event.currentTarget.dataset.v;
    if (!txt) return;
    wx.setClipboardData({
      data: txt.toString(),
      success: function (res) {
        return app.Tips({title: "复制成功", hideMask: true})
      }
    })
  },
  getLists(type) {
    const that = this
    let lists = that.data.lists || {}

    if (that.data.loadend || that.data.loading) {
      wx.stopPullDownRefresh()
      return;
    }

    that.setData({loading: true, loadTitle: '加载更多内容'});
    let filter = {}

    filter['page_num'] = that.data.page;
    filter['advice_id'] = that.data.advice_id;
    filter['limit'] = that.data.limit;

    getAdviceReply(filter).then(res => {
      const list = res.data.items || {};
      const loadend = res.data.last_page <= that.data.page;
      lists = Util.SplitArray(lists, list);

      that.setData({
        lists: lists,
        loadend: loadend,
        loading: false,
        loadTitle: loadend ? '已全部加载' : '加载更多内容',
        et_show: lists.length > 0
      });

      if (that.data.page == 1) {
        that.bottom()
      }

      that.setData({
        page: that.data.page + 1,
      })
      wx.stopPullDownRefresh()
    }).catch(errmsg => {
      that.setData({loading: false, loadTitle: "下拉加载更多"});
      return app.Tips({title: errmsg});
    })

  },

  getInputName(e) {
    this.setData({
      content: e.detail.value || ""
    })
  },

  inputName(e) {
    const content = this.data.content;

    if (Util.isEmpty(content)) {
      return app.Tips({title: "回复内容必填", hideMask: true})
    }

    const that = this
    let lists = this.data.lists || [],
      userInfo = this.data.userInfo,
      advice = this.data.advice

    /* const val = e.detail.value;
     if (Util.isEmpty(val)) {
       return app.Tips({title: "回复内容必填", hideMask: true})
     }*/
    lists.push({
      content: content,
      uid: userInfo.id,
      create_user: {
        avatar: userInfo.avatar || ""
      },
      add_time_format: Util.formatTime()
    })

    that.setData({
      lists: lists,
      content: ''
    })
    setTimeout(() => {
      that.bottom()
    }, 100);
    that.setData({
      lists: lists
    })
    /*let msg = {
      from_uid: this.data.userInfo.id,    //我是谁
      to_uid: advice.uid,    //发送给谁
      type: 'advice',    //当前状态
      action: "reply",
      data: content,
      pid: advice.id
    }
    //调用发送方法，向服务器发送数据
    websocket.sendMsg(msg).then(res => {
      console.log(res)
      console.log("send msg success")
    }).catch(errmsg => {
      console.log(111)
    })*/

    addFeedback({content: content, pid: advice.id}).then(res => {
      lists[lists.length - 1].add_time_format = res.data.data.add_time_format
      that.setData({
        lists: lists
      })
    }).catch(errmsg => {
      app.Tips({title: errmsg})
    });

  },

  imgLoad(e) { //图片加载
    // console.log(e)

    const that = this,
      key = e.currentTarget.dataset.key;
    let lists = that.data.lists;

    if (Util.isEmpty(lists)) return
    lists[key]['radio'] = e.detail.width / e.detail.height

    this.setData({
      lists: lists
    })

  },
  onChooseImage(e) {
    const that = this,
      userInfo = this.data.userInfo;

    let lists = that.data.lists;

    wx.chooseImage({
      count: 1,
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        const url = `${app.globalData.url}/api/add_advice_reply_pic`; // 仅为示例，非真实的接口地址

        lists.push({
          content: "",
          path: tempFilePaths[0],
          uid: userInfo.id,
          create_user: {
            avatar: userInfo.avatar || ""
          },
          add_time_format: Util.formatTime()
        })

        that.setData({
          lists: lists,
        })

        setTimeout(() => {
          that.bottom()
        }, 100);
        that.setData({
          lists: lists
        })

        wx.showLoading({
          title: '正在上传...',
          mask: true,
        })
        wx.uploadFile({
          url: url,
          filePath: tempFilePaths[0],
          name: 'fileData',
          header: {
            token: wx.getStorageSync("cookie_token")
          },
          formData: {
            field_key: 'reply',
            advice_id: that.data.advice_id
          },
          success(res) {
            const data = JSON.parse(res.data);
            if (data.data.add_time_format) {
              lists[lists.length - 1].add_time_format = data.data.add_time_format || "";
            }

            if (data.data.path) {
              lists[lists.length - 1].path = data.data.path || "";
            }
            that.setData({
              lists: lists
            })

            /* const data = JSON.parse(res.data);
             fields[n].default_val = data.data.path;
             that.setData({
               fields: fields
             })*/
            wx.hideLoading()
          }
        });
      },
      fail: function (error) {
      }
    });
  },

  previewSingleImage: function (event) {
    const id = event.currentTarget.dataset.key;
    const imgList = this.data.advice.pictures || [];
    const urls = [];

    const src = Util.previewCdnImage(imgList[id].path, 1028, 0)
    for (let i = 0; i < imgList.length; i++) {
      urls.push(Util.previewCdnImage(imgList[i].path, 1028, 0));
    }

    if (urls.length > 0) {
      wx.previewImage({
        current: src,
        urls: urls
      });
    }
  },

  previewImage(e) {//单张图片预览
    let src = e.currentTarget.dataset.src
    let images = []

    if (Util.isEmpty(src)) return;
    src = Util.previewCdnImage(src, 1080, 0);

    images.push(src)
    wx.previewImage({
      current: src,
      urls: images,
    });
  },

  // 获取hei的id节点然后屏幕焦点调转到这个节点
  bottom: function () {
    var query = wx.createSelectorQuery()
    query.select('#hei').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function (res) {
      wx.pageScrollTo({
        scrollTop: res[1].scrollHeight  // #the-id节点的下边界坐标
      })
      res[1].scrollTop // 显示区域的竖直滚动位置
    })
  },

  onLoadTabbar: function () {//底部tabbar返回数据
    const that = this
    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({isIphoneX: res})

      wx.createSelectorQuery().in(that).select('#weui-footer')
        .boundingClientRect(function (rect) {
          if (!rect) return;
          that.setData({
            bottom: parseInt(rect.height) + 15
          })
        }).exec()

    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    websocket.closeConnect()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getLists()
  },

  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})